package com.zlm.config;


import com.zlm.filter.VerifyCodeFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * springsecurity配置
 */

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    // 配置数据源
    public UserDetailsService userDetailsService() {
        InMemoryUserDetailsManager userDetailsManager = new InMemoryUserDetailsManager();
        userDetailsManager.createUser(User.withUsername("root").password("{noop}1234").roles("admin").build());
        return userDetailsManager;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService());
    }

    // 暴露出来
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    // 加入工厂
    @Bean
    public VerifyCodeFilter verifyCodeFilter() throws Exception {
        // 相当于这些你要全部重写一遍
        VerifyCodeFilter verifyCodeFilter = new VerifyCodeFilter();
        verifyCodeFilter.setFilterProcessesUrl("/doLogin");
        verifyCodeFilter.setUsernameParameter("uname");
        verifyCodeFilter.setPasswordParameter("passwd");
        verifyCodeFilter.setKaptchaParameter("verifyCode");

        // 指定认证管理器
        verifyCodeFilter.setAuthenticationManager(authenticationManagerBean());

        // 指定认证成功处理
        verifyCodeFilter.setAuthenticationSuccessHandler((req, resp, auth) -> {
            resp.sendRedirect("/index.html");
        });
        // 指定认证失败处理
        verifyCodeFilter.setAuthenticationFailureHandler(((req, resp, exception) -> {
            resp.sendRedirect("/login.html");
            // 你要自己去保存一下这个异常处理 ，因为自定义的话就什么都没有的
        }));


        return verifyCodeFilter;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests()
                .mvcMatchers("/login.html").permitAll() // 进行放行
                .mvcMatchers("/vc.jpg").permitAll() // 进行放行
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/login.html")
//                .loginProcessingUrl("/doLogin")
//                .usernameParameter("uname")
//                .passwordParameter("pwd")
//                .defaultSuccessUrl("/index.html", true) // 重定向到index.html
//                .failureUrl("/login.html") // 失败的重定向
                .and()
                .logout()
                .logoutUrl("/logout")
                .and()
                .csrf().disable();

        // 替换userNamePasswordAuthenticationFilter
        http.addFilterAt(verifyCodeFilter(), UsernamePasswordAuthenticationFilter.class);
    }
}
